//
//  ZLTextField.swift
//  ZLKit_Swift
//
//  Created by 赵磊 on 2022/8/20.
//

import Foundation

open class ZLTextField: UITextField {
    
    public enum ImportType: Int {
        /// 中文
        case chinese
        /// 数字 0~9  电话号码
        case number
        /// 密码
        case password
        /// 身份证号码
        case identityCardID
        /// 邮箱
        case email
    }
    
    public var maxLength: Int = 0
    
    /// 输入改变
    public var editingChangedHandler: Params_one_void<String?> = nil
    
    /// 第一响应者事件监听
    public var firstResponderHandler: Params_one_void<Bool> = nil
    
    /// 安全性处理事件
    public var secureTextEntryHandler: Params_one_void<Bool> = nil
    
    open override var isSecureTextEntry: Bool {
        didSet {
            secureTextEntryHandler?(isSecureTextEntry)
        }
    }
    
    deinit {
        removeNotification(name: .textFieldTextDidChange, observer: self)
    }
    
    /// 工具条
    lazy var _inputAccessoryView: UIView = {
        let view = UIView(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
        view.backgroundColor = .hex_FFFFFF
        return view
    }()
    
    /// 完成
    lazy var doneItem: UILabel = {
        let view = UILabel()
        view.text = "完成"
        view.font = .pingFangSC(ofSize: 15, weight: .medium)
        view.textColor = .hex_333333
        view.textAlignment = .center
        view.action.tap = {[weak self] _ in
            self?.resignFirstResponder()
        }
        return view
    }()
   
    public init(type: ImportType = .chinese) {
        super.init(frame: .zero)
        if type == .number {
            keyboardType = .numberPad
        }
        autocapitalizationType = .none
        autocorrectionType = .no
        inputAccessoryView = _inputAccessoryView
        returnKeyType = .done
        delegate = self
        addNotification(name: .textFieldTextDidChange, observer: self, selector: #selector(editingChangedAction(_:)))
        addSubviews()
        addConstraints()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func addSubviews() {
        _inputAccessoryView.addSubview(doneItem)
    }
    
    private func addConstraints() {
        doneItem.snp.makeConstraints {
            $0.centerY.equalToSuperview()
            $0.trailing.equalToSuperview().inset(15)
        }
    }
    
    @discardableResult
    open override func becomeFirstResponder() -> Bool {
        firstResponderHandler?(true)
        return super.becomeFirstResponder()
    }
    
    @discardableResult
    open override func resignFirstResponder() -> Bool {
        firstResponderHandler?(false)
        return super.resignFirstResponder()
    }
    
}

// 事件区
extension ZLTextField: UITextFieldDelegate {
    
    @objc func editingChangedAction(_ notifi: Notification) {
        let textField: UITextField = notifi.object as? UITextField ?? .init()
        guard textField == self else { return }
        guard let _: UITextRange = textField.markedTextRange else {
            if ((textField.text ?? "") as NSString).length >= maxLength && maxLength > 0 {
                textField.text = (textField.text! as NSString).substring(to: maxLength)
                editingChangedHandler?(textField.text ?? "")
            }else {
                editingChangedHandler?(textField.text ?? "")
            }
            return
        }
    }
    
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.endEditing(false)
        return true
    }
    
}

// 定制区
extension ZLTextField {
    
    
    
}
